import Vue from 'vue'
import {
  setToken, setCustomerId, setPhone, setVisitorId, setEnterpriseId, setVeekrayStatus,
  setShowBuyCard, setStoreCardFlag, setMemberNature, setMemberId, setCustomerCommanderStatus } from '@/utils/auth'
import { getMemberInfo } from '@/api/home'

let vue = new Vue()

export function checkLogin(memberId, customerId) {
  console.log('memberId:' + memberId)
  console.log('customerId:' + customerId)
  // 检查memberId 是否有效
  if (memberId) {
    getMemberInfo(memberId).then((response) => {
      if (response.isError) {
        // 如果会员id不存在，不传入会员id
        ptLogin()
      } else {
        setStoreCardFlag(response.data.storeCardFlag)
        setMemberNature(response.data.nature)
        ptLogin(memberId)
      }
    }).catch(() => {
    })
  } else {
    ptLogin()
  }
}

// 区分平台登录
export function ptLogin(memberId) {
  if (vue.$platform === 'wx') {
    wxLogin(memberId)
  }
}

export function wxLogin(memberId) {
  vue.$pt.login({
    success(res) {
      if (res.code) {
        console.log('login:' + res.code)
        getAuth(res.code).then((response) => {
          // console.log(response)
          if (response.isError) {
            // 出错重新登录
            setTimeout(() => {
              wxLogin(memberId)
            }, 3000)
            return
          }
          if (response.data.customerId) {
            setCustomerId(response.data.customerId)
          } else {
            setCustomerId('')
          }
          if (response.data.phone) {
            setPhone(response.data.phone)
          } else {
            setPhone('')
          }
          if (response.data.visitorId) {
            setVisitorId(response.data.visitorId)
          } else {
            setVisitorId('')
          }
          if (response.data.enterpriseId) {
            setEnterpriseId(response.data.enterpriseId)
          }
          setToken(response.data.token)
          setVeekrayStatus(response.data.veekrayStatus)
          setShowBuyCard(response.data.showBuyCard)
          // 设置团长身份状态
          if (response.data.commanderStatus === 1) {
            setCustomerCommanderStatus(response.data.commanderStatus)
          }
          // 如果memberId为空，跳回首页
          let appStorageInfo = vue.$pt.getStorageSync('appInfo')
          // console.log('appInfo login 111')
          // console.log(appStorageInfo)
          if (!memberId) {
            // veekrayStatus 萤火微客注册状态 -1:未注册 0:免费名片 1:付费名片
            if (response.data.veekrayStatus !== -1 && response.data.veekrayStatus !== 0) {
              // 回到自己到名片
              memberEls(response.data.customerId)
            } else {
              if (response.data.customerId) {
                // 未购买主页、默认访问主页人
                if (response.data.lastAccessMemberId === appStorageInfo.defaultMemberId || response.data.lastAccessMemberId === '1123207778244132865') {
                  memberEls(appStorageInfo.defaultMemberId)
                } else {
                  // 未购买主页、已访问默认主页，再次切换了主页后，前往最后一次访问的主页
                  if (response.data.customerId === response.data.lastAccessMemberId) {
                    memberEls(appStorageInfo.defaultMemberId)
                  } else {
                    memberEls(response.data.lastAccessMemberId)
                  }
                }
              } else {
                // 用户没有授权 以游客模式登陆 使用defaultMemberId
                memberEls(appStorageInfo.defaultMemberId)
              }
            }
          }
          // 初次账号新用户查看名片首页处理
          if (response.data.showBuyCard === false) {
            memberEls(appStorageInfo.defaultMemberId)
          }
        }).catch(() => {
        })
      } else {
        vue.$utils.showToast({ title: '登录失败' })
      }
    }
  })
}

export function memberEls(memberId) {
  setMemberId(memberId)
  vue.$utils.setMyId(memberId)
  if (vue.$pt.getStorageSync('messageListIn')) {
    vue.$pt.reLaunch({ url: '/pages/personal/message/list/main' })
    return
  }
  if (vue.$pt.getStorageSync('homeNone')) {
    vue.$pt.reLaunch({ url: '/pages/home/main' })
    vue.$pt.removeStorageSync('homeNone')
  }
}

/*
  接口地址 /api/wechat/auth
  请求方式 GET
  接口描述 小程序登录认证
*/
export function getAuth(code) {
  return vue.$fly.request({
    url: '/wechat/auth',
    method: 'get',
    params: {
      code: code,
      version: Math.floor(process.env.VERSION)
    }
  })
}
